﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Utils;
using LevenBlog.Core.Service;
using LevenBlog.Core.Mvc;
using LevenBlog.Core.Cache;
using LevenBlog.Core.User;

namespace LevenBlog.Web.Controllers
{
    [HandleBlogError]
    [ValidateInput(false)]
    public class AdminController : AdminBaseController
    {
        public AdminController()
        {
            ViewData["manager"] = Membership.User;
            ViewData["managerauthority"] = Membership.Authority;
        }

        [ManagerAuthorize(IsManager=false)]
        public ActionResult Login()
        {
            return View("login");
        }

        [ManagerAuthorize]
        public ActionResult Index()
        {
            return View("index");
        }

        [ManagerAuthorize]
        public ActionResult Head()
        {
            return View("head");
        }

        [ManagerAuthorize]
        public ActionResult Menu()
        {
            return View("menu");
        }

        [ManagerAuthorize]
        public ActionResult Main()
        {
            ViewData["config"] = LevenBlog.Core.Service.Config.Get(Provider);
            ViewData["state"] = State.Get(Provider);
            ViewData["modules"] = Fetch.GetLoadedAssemblyNames();
            return View("main");
        }

        [ManagerAuthorize(IsManager=false)]
        public ActionResult LoginCheck()
        {
            string username = Request.Form["username"];
            string password = Request.Form["password"];
            string code = Request.Form["code"];
            username = username == null ? string.Empty : username.Trim();
            password = password == null ? string.Empty : password.Trim();
            code = code == null ? string.Empty : code.Trim();
            HttpCookie codeCookie = Request.Cookies.Get(WebConfig.PrefixKey + "CheckCode");
            if (codeCookie == null)
            {
                ViewData["message"] = "验证码过期,请返回重新输入.";
                return View("login");
            }
            else
            {
                if (code.ToLower().ToMD5() != codeCookie.Value)
                {
                    ViewData["message"] = "验证码输入错误,请返回重新上输入.";
                    return View("login");
                }
                else
                    Response.Cookies.Remove(WebConfig.PrefixKey + "CheckCode");
            }
            if (string.IsNullOrEmpty(username) | string.IsNullOrEmpty(password))
            {
                ViewData["message"] = "用户名或者密码为空.";
                return View("login");
            }
            if (!Membership.Login(username, password))
            {
                ViewData["message"] = "用户名或者密码错误,请重新输入.";
                return View("login");
            }
            else
            {
                return RedirectToAction("index");
            }
        }

        [ManagerAuthorize]
        public ActionResult Logout()
        {
            Membership.Logout();
            return RedirectToRoute(new { controller = "blog", action = "index", page = "1" });
        }

        [ManagerAuthorize("Config")]
        public ActionResult Info()
        {
            return View("info");
        }

        [ManagerAuthorize("Config")]
        public ActionResult Config()
        {
            ViewData.Model = LevenBlog.Core.Service.Config.Get(Provider);
            return View("config");
        }

        [ManagerAuthorize("Config")]
        public ActionResult ConfigPost()
        {
            DateTime buildtime = DateTime.Now;
            if (!DateTime.TryParse(Request.Form["buildtime"], out buildtime))
            {
                return Message("时间格式错误", "您提交的站点建立时间格式错误.", MessageIcon.Error);
            }
            lb_config config = LevenBlog.Core.Service.Config.Get(Provider);
            config.badchars = Request.Form["badchars"].FormEncode();
            config.badip = Request.Form["badip"].FormEncode();
            config.baduser = Request.Form["baduser"].FormEncode();
            int temp = config.blogpage;
            int.TryParse(Request.Form["blogpage"], out temp);
            config.blogpage = temp;
            temp = config.commentpage;
            int.TryParse(Request.Form["commentpage"], out temp);
            config.commentpage = temp;
            config.buildtime = buildtime;
            config.copyright = Request.Form["copyright"].FormEncode();
            config.intro = Request.Form["intro"].FormEncode();
            config.iscomment = Request.Form["iscomment"].ToBoolean();
            config.isreg = Request.Form["isreg"].ToBoolean();
            config.istrack = Request.Form["istrack"].ToBoolean();
            config.isupload = Request.Form["isupload"].ToBoolean();
            config.isopen = Request.Form["isopen"].ToBoolean();
            config.logo = Request.Form["logo"].FormEncode();
            config.mail = Request.Form["mail"].FormEncode();
            config.master = Request.Form["master"].FormEncode();
            temp = config.posttime;
            int.TryParse(Request.Form["posttime"], out temp);
            config.posttime = temp;
            config.tcp = Request.Form["tcp"].FormEncode();
            config.title = Request.Form["title"].FormEncode();
            config.uploadfiles = Request.Form["uploadfiles"].FormEncode();
            config.uploadpath = Request.Form["uploadpath"].FormEncode();
            temp = config.uploadsize;
            int.TryParse(Request.Form["uploadsize"], out temp);
            config.uploadsize = temp;
            config.url = Request.Form["url"];
            config.issmtp = Request.Form["issmtp"].ToBoolean();
            config.smtpsender = Request.Form["smtpsender"].FormEncode();
            config.smtpserver = Request.Form["smtpserver"].FormEncode();
            config.smtpuser = Request.Form["smtpuser"].FormEncode();
            config.smtppassword = Request.Form["smtppassword"].FormEncode();
            LevenBlog.Core.Service.Config.Update(Provider, config);
            return Message("系统配置修改成功", "恭喜,您成功对系统配置信息进行了修改.", MessageIcon.Message);
        }

        [ManagerAuthorize("Config")]
        public ActionResult ClearCache()
        {
            ObjectCache.RemoveAll();
            Archive.Remove();
            LevenBlog.Core.Service.Category.Remove();
            LevenBlog.Core.Service.Config.Remove();
            ImageType.Remove();
            FriendLink.Remove();
            State.Remove();
            UserType.Remove();
            CalendarCache.Clear();
            Blog.Clear();
            GC.Collect();
            return Message("清除缓存成功", "您已经清除了站点的所有缓存.", MessageIcon.Message);
        }

        [ManagerAuthorize("Category")]
        public ActionResult Category()
        {
            ViewData.Model = LevenBlog.Core.Service.Category.Get(Provider);
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "category", string.Empty, ViewData, TempData));
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "category", ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData));
            string iconsPath = Url.Content("~/skins/" + LevenBlog.Core.Service.Config.Get(Provider).skinpath + "/images/icons");
            ViewData["iconpath"] = iconsPath;
            ViewData["skinpath"] = "skins/" + LevenBlog.Core.Service.Config.Get(Provider).skinpath + "/";
            iconsPath = Server.MapPath(iconsPath);
            if (!System.IO.Directory.Exists(iconsPath))
                throw new System.IO.DirectoryNotFoundException("分类Icon目录未找到,请检查目前模板下的\"images/icons\"目录是否存在.");
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(iconsPath);
            IList<string> iconList = new List<string>();
            foreach (System.IO.FileInfo f in di.GetFiles())
            {
                iconList.Add(f.Name);
            }
            ViewData["icons"] = iconList;
            return View("category");
        }

        [ManagerAuthorize("Category")]
        public ActionResult CategoryPost()
        {
            //string result = string.Empty;
            //for (int i = 0; i < Request.Form.Count; i++)
            //{
            //    result += string.Format("{0}={1}<br />", Request.Form.Keys[i], Request.Form[i]);
            //}
            string idString = Request.Form["id"];
            //如果已经存在分类,将更新分类信息
            if (!string.IsNullOrEmpty(idString))
            {
                string[] idArray = idString.Split(',');
                if (string.IsNullOrEmpty(Request.Form["icons"]) || string.IsNullOrEmpty(Request.Form["new_icons"]))
                    return Message("错误的分类图标信息", "您提交了错误的分类图标信息.", MessageIcon.Error);
                string[] imageArray = Request.Form["icons"].Split(',');
                IList<lb_category> categoryList = LevenBlog.Core.Service.Category.Get(Provider);
                for(int i=0;i<categoryList.Count;i++)
                {
                    categoryList[i].image = imageArray[i].Substring(imageArray[i].LastIndexOf("/images") + 1);
                    categoryList[i].info = Request.Form["info_" + categoryList[i].id].FormEncode();
                    categoryList[i].isurl = Request.Form["isurl_" + categoryList[i].id].ToBoolean();
                    categoryList[i].name = Request.Form["name_" + categoryList[i].id].FormEncode();
                    categoryList[i].order = Request.Form["order_" + categoryList[i].id].ToInt32(categoryList[i].order);
                    categoryList[i].url = Request.Form["url_" + categoryList[i].id].FormEncode();
                    categoryList[i].view = Convert.ToInt16(Request.Form["view_" + categoryList[i].id].ToInt32(0));
                }
                LevenBlog.Core.Service.Category.Update(Provider, categoryList.ToArray());
            }
            if (!string.IsNullOrEmpty(Request.Form["new_name"]))
            {
                lb_category category = new lb_category();
                category.image = Request.Form["new_icons"].Substring(Request.Form["new_icons"].LastIndexOf("/images") + 1);
                category.info = Request.Form["new_info"].FormEncode();
                category.isurl = Request.Form["new_isurl"].ToBoolean();
                category.name = Request.Form["new_name"].FormEncode();
                category.num = 0;
                category.order = Request.Form["new_order"].ToInt32(1000);
                category.url = Request.Form["new_url"].FormEncode();
                category.view = Convert.ToInt16(Request.Form["new_view"].ToInt32());
                LevenBlog.Core.Service.Category.Insert(Provider, category);
            }
            return Message("操作成功", "日志分类更新成功.", new { controller = "admin", action = "category" }, "返回分类管理", MessageIcon.Message);
        }

        [ManagerAuthorize("Category")]
        public ActionResult CategoryDelete(int? id)
        {
            id = id ?? 0;
            if (id.Value < 0)
                return Message("参数错误", "您提交的参数有误.", MessageIcon.Error);
            LevenBlog.Core.Service.Category.Delete(Provider, id.Value);
            return Message("操作成功", "指定的日志分类删除成功.", new { controller = "admin", action = "category" }, "返回分类管理", MessageIcon.Message);
        }

        [ManagerAuthorize("ManageComment")]
        public ActionResult Comment(int? page, int? pagesize)
        {
            page = page ?? 1;
            pagesize = pagesize ?? 20;
            ViewData.Model = LevenBlog.Core.Service.Comment.Get(Provider, pagesize.Value, page.Value, CommentState.None);
            ViewData["recordcount"] = LevenBlog.Core.Service.Comment.Count(Provider, CommentState.Show);
            ViewData["pagesize"] = pagesize.Value;
            return View("comment");
        }

        [ManagerAuthorize("ManageComment")]
        public ActionResult CommentVerify(int? id, int? verify)
        {
            id = id ?? 0;
            verify = verify ?? -1;
            if (id < 1)
                return Message("评论错误", "错误的评论编号.", MessageIcon.Error);
            if (verify < 0)
                return Message("评论审核错误", "错误的操作.", MessageIcon.Error);
            lb_comment comment = LevenBlog.Core.Service.Comment.Get(Provider, id.Value);
            if (comment == null)
                return Message("审核错误", "对不起,您请求操作的评论不存在或者已经被删除.", MessageIcon.Error);
            if (verify == 0)
                comment.isshow = false;
            else if (verify == 1)
                comment.isshow = true;
            else
                return Message("操作错误", "对不起,系统不支持该操作.", MessageIcon.Error);
            LevenBlog.Core.Service.Comment.Update(Provider, comment);
            ObjectCache.RegexRemove(".*?comment.*?");
            return Message("审核成功", "对评论的审核操作成功.", new { controller = "admin", action = "comment", page = "1" },"返回评论管理", MessageIcon.Message);
        }

        [ManagerAuthorize("ManageComment")]
        public ActionResult CommentEdit()
        {
            string content = Request.Form["content"];
            int id = Request.Form["id"].ToInt32(0);
            bool ishtml = Request.Form["ishtml"].ToBoolean();
            if (id < 1)
                return Json(new { info = "参数错误.", back = content });
            if (string.IsNullOrEmpty(content))
                return Json("评论内容不能为空.");
            lb_comment comment = LevenBlog.Core.Service.Comment.Get(Provider, id);
            if (comment == null)
                return Json(new { info = "指定的评论不存在或者已经被删除.", back = content });
            if (ishtml)
                comment.content = content;
            else
                comment.content = content.HtmlEncode();
            try
            {
                LevenBlog.Core.Service.Comment.Update(Provider, comment);
            }
            catch
            {
                return Json(new { info = "修改评论失败.", back = content });
            }
            return Json(new { info = "评论编辑成功.", back = content });
        }

        [ManagerAuthorize("ManageComment")]
        public ActionResult CommentDelete(string idarray)
        {
            if (string.IsNullOrEmpty(idarray))
                return Message("参数错误", "你提交了错误的URL参数.", MessageIcon.Error);
            string[] sArray = idarray.Trim().Split(',');
            IList<int> idList = new List<int>();
            int temp = 0;
            foreach (string ids in sArray)
            {
                if (!int.TryParse(ids, out temp))
                {
                    return Message("参数错误", "您提交了错误的URL参数.", MessageIcon.Error);
                }
                else
                {
                    idList.Add(temp);
                }
            }
            foreach (int id in idList)
            {
                LevenBlog.Core.Service.Comment.Delete(Provider, id);
            }
            ObjectCache.RegexRemove(".*?comment.*?");
            ObjectCache.RegexRemove(".*?blog.*?");
            return Message("操作成功", "恭喜,指定的评论已经被删除.", new { controller = "admin", action = "comment", page = "1" }, "返回评论管理", MessageIcon.Message);
        }

        [ManagerAuthorize("ManageTrack")]
        public ActionResult Track(int? page, int? pagesize)
        {
            page = page ?? 1;
            pagesize = pagesize ?? 20;
            ViewData.Model = LevenBlog.Core.Service.Track.Get(Provider, pagesize.Value, page.Value);
            ViewData["recordcount"] = LevenBlog.Core.Service.Track.Count(Provider);
            ViewData["pagesize"] = pagesize.Value;
            return View("track");
        }

        [ManagerAuthorize("ManageTrack")]
        public ActionResult TrackDelete(string idarray)
        {
            if (string.IsNullOrEmpty(idarray))
                return Message("参数错误", "你提交了错误的URL参数.", MessageIcon.Error);
            string[] sArray = idarray.Trim().Split(',');
            IList<int> idList = new List<int>();
            int temp = 0;
            foreach (string ids in sArray)
            {
                if (!int.TryParse(ids, out temp))
                {
                    return Message("参数错误", "您提交了错误的URL参数.", MessageIcon.Error);
                }
                else
                {
                    idList.Add(temp);
                }
            }
            foreach (int id in idList)
            {
                LevenBlog.Core.Service.Track.Delete(Provider, id);
            }
            ObjectCache.RegexRemove(".*?track.*?");
            ObjectCache.RegexRemove(".*?blog.*?");
            return Message("操作成功", "恭喜,指定的引用已经被删除.", new { controller = "admin", action = "track", page = "1" }, "返回引用管理", MessageIcon.Message);
        }

        [ManagerAuthorize("Config")]
        public ActionResult Skin()
        {
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "skin", "", ViewData, TempData));
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "skin", ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData));
            string skinvpath = Url.Content("~/skins/");
            string skinrpath = Server.MapPath(skinvpath);
            if (!System.IO.Directory.Exists(skinrpath))
                return Message("系统模板错误", "对不起,未找到任何模板,请至少放一套模板至系统Skin目录.", MessageIcon.Error);
            SkinManager skinManager = new SkinManager(skinrpath, skinvpath);
            ViewData.Model = skinManager.Get();
            ViewData["config"] = LevenBlog.Core.Service.Config.Get(Provider);
            return View("skin");
        }

        [ManagerAuthorize("Config")]
        public ActionResult SkinChange(string path)
        {
            if (string.IsNullOrEmpty(path))
                return Message("参数错误", "您提交的参数错误.", MessageIcon.Error);
            path = path.ToFileName();
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "skin", "", ViewData, TempData));
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "skin", ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData));
            string skinvpath = Url.Content("~/skins/");
            string skinrpath = Server.MapPath(skinvpath);
            if (!System.IO.Directory.Exists(skinrpath))
                return Message("系统模板错误", "对不起,未找到任何模板,请至少放一套模板至系统skins目录.", MessageIcon.Error);
            SkinManager skinManager = new SkinManager(skinrpath, skinvpath);
            SkinEntity skin = skinManager.Get(skinrpath.AppendPath(path).AppendPath("skin.xml"), path);
            if (skin == null)
                return Message("模板设置错误", "对不起不存在您提交的模板,请检查您的模板是否放入了skins目录.", MessageIcon.Error);
            lb_config config = LevenBlog.Core.Service.Config.Get(Provider);
            config.skinauthor = skin.Designer;
            config.skinname = skin.Name;
            config.skinpath = path;
            config.skinurl = skin.Url;
            LevenBlog.Core.Service.Config.Update(Provider, config);
            IViewEngine viewengine = ViewEngines.Engines.FirstOrDefault(v => v.GetType() == typeof(BlogViewEngine));
            if (viewengine == null)
            {
                ViewEngines.Engines.Add(new BlogViewEngine(config.skinpath));
            }
            else
            {
                ViewEngines.Engines.Remove(viewengine);
                ViewEngines.Engines.Add(new BlogViewEngine(config.skinpath));
            }
            LevenBlog.Core.Service.Config.Remove();
            Log.Write(Provider, new lb_log() {
                ip = Fetch.UserIp,
                message = "重新配置模板,新模板路径为:" + config.skinpath,
                page = Url.Action("skinchange"),
                time = DateTime.Now,
                user = Membership.User.name
            });
            return Message("模板配置成功", "恭喜,您已经成功更换系统模板.", new { controller = "admin", action = "skin" }, "返回模板管理", MessageIcon.Message);
        }

        [ManagerAuthorize("File")]
        public ActionResult UpFile(int? page, int? pagesize)
        {
            page = page ?? 1;
            pagesize = pagesize ?? 20;
            ViewData.Model = LevenBlog.Core.Service.File.Get(Provider, pagesize.Value, page.Value);
            ViewData["recordcount"] = LevenBlog.Core.Service.File.Count(Provider);
            ViewData["pagesize"] = pagesize.Value;
            return View("upfile");
        }

        [ManagerAuthorize("File")]
        public ActionResult FileDelete(string idarray)
        {
            if (string.IsNullOrEmpty(idarray))
                return Message("参数错误", "你提交了错误的URL参数.", MessageIcon.Error);
            string[] sArray = idarray.Trim().Split(',');
            IList<int> idList = new List<int>();
            int temp = 0;
            foreach (string ids in sArray)
            {
                if (!int.TryParse(ids, out temp))
                {
                    return Message("参数错误", "您提交了错误的URL参数.", MessageIcon.Error);
                }
                else
                {
                    idList.Add(temp);
                }
            }
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "filedelete", "", ViewData, TempData));
            //UrlHelper url = new UrlHelper(new ViewContext(ControllerContext, "filedelete", ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData));
            string upvpath = Url.Content(LevenBlog.Core.Service.Config.Get(Provider).uploadpath);
            string upfpath = Server.MapPath(upvpath);
            if (!System.IO.Directory.Exists(upfpath))
                return Message("上传路径错误", "系统设置的上传目录不存在或者无权访问.", MessageIcon.Error);
            foreach (int id in idList)
            {
                lb_file file = LevenBlog.Core.Service.File.Get(Provider, id);
                if (System.IO.File.Exists(upfpath.AppendPath(file.path).AppendPath(file.name)))
                {
                    try
                    {
                        System.IO.File.Delete(upfpath.AppendPath(file.path).AppendPath(file.name));
                    }
                    catch
                    {
                        return Message("删除文件出错.", string.Format("删除{0}出错,磁盘出错或者您无权删除该文件.", file.name), MessageIcon.Error);
                    }
                }
                LevenBlog.Core.Service.File.Delete(Provider, id);
            }
            return Message("操作成功", "恭喜,选中的文件已经被删除.", new { controller = "admin", action = "upfile", page = "1" }, "返回附件管理", MessageIcon.Message);
        }

        [ManagerAuthorize("UserType")]
        public ActionResult Role()
        {
            ViewData.Model = UserType.Get(Provider);
            return View("role");
        }

        [ManagerAuthorize("Super")]
        public ActionResult RoleAdd()
        {
            lb_usertype type = new lb_usertype();
            type.name = Request.Form["new_name"].FormEncode();
            type.intro = Request.Form["new_intro"].FormEncode();
            if (string.IsNullOrEmpty(type.name) || string.IsNullOrEmpty(type.intro))
            {
                return Message("数据提交错误", "对不起,您提交的新用户组信息不完整,请完整填写后提交.", MessageIcon.Error);
            }
            if (UserType.Get(Provider, type.name) != null)
            {
                return Message("增加新用户在错误", "您提交的用户组已经存在,请再次检查您的输入.", MessageIcon.Error);
            }
            //获取一般权限.
            Authority au = new Authority();
            type.competence = au.ToCode();
            UserType.Insert(Provider, type);
            return Message("增加用户组成功", "恭喜,增加新的用户组成功,接下来您可以对该组进行权限分配.", new { controller = "admin", action = "role" }, "返回用户组管理", MessageIcon.Error);
        }

        [ManagerAuthorize("Super")]
        public ActionResult RoleDelete(int? id)
        {
            if (id.Value < 1)
                return Message("参数错误", "你提交了错误的URL参数.", MessageIcon.Error);
            if (UserType.Get(Provider, id.Value) == null)
            {
                return Message("参数错误", "该用户组不存在或者已经被删除.", MessageIcon.Error);
            }
            try
            {
                UserType.Delete(Provider, id.Value);
            }
            catch (Exception e)
            {
                return Message("删除用户组错误", e.Message, MessageIcon.Error);
            }
            return Message("删除用户组成功", "删除指定的用户组成功.", new { controller = "admin", action = "role" }, "返回用户组管理", MessageIcon.Error);
        }

        [ManagerAuthorize("Super")]
        public ActionResult RoleEdit(int? id)
        {
            if (id.Value < 1)
                return Message("参数错误", "你提交了错误的URL参数.", MessageIcon.Error);
            if (UserType.Get(Provider, id.Value) == null)
            {
                return Message("参数错误", "该用户组不存在或者已经被删除.", MessageIcon.Error);
            }
            lb_usertype type = UserType.Get(Provider, id.Value);
            ViewData.Model = type;
            Dictionary<string, string> authCode = new Dictionary<string, string>();
            string[] sp = type.competence.Split('|');
            foreach (string s in sp)
            {
                string[] auarr = s.Split('=');
                authCode.Add(auarr[0].Trim(), auarr[1].Trim());
            }
            ViewData["authcode"] = authCode;
            return View("roleedit");
        }

        [ManagerAuthorize("Super")]
        public ActionResult RoleEditPost(int? id)
        {
            if (id.Value < 1)
                return Message("参数错误", "你提交了错误的URL参数.", MessageIcon.Error);
            string q = Request.Form.ToString();
            lb_usertype type = UserType.Get(Provider, id.Value);
            if (type == null)
            {
                return Message("参数错误", "该用户组不存在或者已经被删除.", MessageIcon.Error);
            }
            Authority au = new Authority();
            try
            {
                au.FillWithWebRequest(Request);
            }
            catch(Exception e)
            {
                return Message("输入错误", e.Message, MessageIcon.Error);
            }
            type.intro = Request.Form["intro"].FormEncode();
            type.competence = au.ToCode();
            UserType.Update(Provider, type);
            return Message("用户组更新成功", "该用户组的权限成功更新.", new { controller = "admin", action = "role" }, "返回用户组管理", MessageIcon.Message);
        }

        [ManagerAuthorize("User")]
        public ActionResult UserList(int? page, int? pagesize)
        {
            page = page ?? 1;
            pagesize = pagesize ?? 20;
            IList<lb_user> users = BlogUser.GetAll(Provider, pagesize.Value, page.Value);
            ViewData.Model = users;
            ViewData["recordcount"] = BlogUser.Count(Provider);
            ViewData["pagesize"] = pagesize.Value;
            return View("userlist");
        }

        [ManagerAuthorize("User")]
        public ActionResult UserSearch(int? page,int? pagesize)
        {
            page = page ?? 1;
            pagesize = pagesize ?? 20;
            string name = Request.QueryString["name"];
            if (string.IsNullOrEmpty(name))
                return Message("输入有误", ",请输入要搜索的用户名.", MessageIcon.Error);
            name = name.FormEncode().SqlEncode();
            int count = BlogUser.Count(Provider, name);
            if (count < 1)
                return Message("未找到记录", "未找到要搜索的用户.", MessageIcon.Error);
            ViewData["recordcount"] = count;
            ViewData.Model = BlogUser.SearchAll(Provider, name, pagesize.Value, page.Value);
            ViewData["pagesize"] = pagesize.Value;
            return View("userlist");
        }

        [ManagerAuthorize("Super")]
        public ActionResult UserEdit(int? id)
        {
            id = id ?? 0;
            if (id.Value < 1)
                return Message("参数错误", "输入参数错误.", MessageIcon.Error);
            lb_user user = BlogUser.Get(Provider, id.Value);
            ViewData.Model = user;
            ViewData["roles"] = UserType.Get(Provider);
            return View("useredit");
        }

        [ManagerAuthorize("Super")]
        public ActionResult UserEditPost(int? id)
        {
            id = id ?? 0;
            if (id.Value < 1)
                return Message("参数错误", "输入参数错误.", MessageIcon.Error);
            lb_user user = BlogUser.Get(Provider, id.Value);
            if (user == null)
                return Message("参数错误", "您要修改的用户不存在或者已经被删除.", MessageIcon.Error);
            if (!string.IsNullOrEmpty(Request.Form["password"]))
                user.password = Request.Form["password"].FormEncode().ToMD5();
            int typeid = Request.Form["typeid"].ToInt32();
            if (typeid > 0)
                user.typeid = typeid;
            DateTime time = DateTime.Now;
            if (DateTime.TryParse(Request.Form["birthday"], out time))
                user.userinfo.birthday = time;
            user.userinfo.face = Request.Form["face"].FormEncode();
            user.userinfo.mail = Request.Form["mail"].FormEncode();
            user.userinfo.nickname = Request.Form["nickname"].FormEncode();
            user.userinfo.sex = Convert.ToInt16(Request.Form["sex"].ToInt32(user.userinfo.sex));
            user.userinfo.signature=Request.Form["signature"];
            BlogUser.Update(Provider,user);
            return Message("修改成功", "用户资料修改成功.", new { controller = "admin", action = "userlist" }, "返回用户管理", MessageIcon.Message);
        }

        [ManagerAuthorize("Config")]
        public ActionResult Link()
        {
            ViewData.Model = FriendLink.Get(Provider);
            return View("link");
        }

        [ManagerAuthorize("Config")]
        public ActionResult LinkEditPost()
        {
            int id = 0;
            if (!int.TryParse(Request.Form["id"], out id))
            {
                return Json(new { result = false, info = "参数错误" });
            }
            lb_friendlink link = FriendLink.Get(Provider, id);
            if (link == null)
                return Json(new { result = false, info = "无法获取原始链接信息." });
            link.image = Request.Form["image"].FormEncode();
            link.intro = Request.Form["intro"].FormEncode();
            link.name = Request.Form["name"].FormEncode();
            link.order = Request.Form["order"].ToInt32(link.order);
            link.url = Request.Form["url"].FormEncode();
            link.isimg = Request.Form["isimg"].ToBoolean();
            link.isindex = Request.Form["isindex"].ToBoolean();
            link.isshow = Request.Form["isshow"].ToBoolean();
            try
            {
                FriendLink.Update(Provider, link);
                return Json(new { result = true, info = "友情链接数据更新成功." });
            }
            catch
            {
                return Json(new { result = false, info = "友情链接数据更新失败." });
            }
        }

        [ManagerAuthorize("Config")]
        public ActionResult LinkDelete(int? id)
        {
            id = id ?? 0;
            lb_friendlink link = FriendLink.Get(Provider, id.Value);
            if (link == null)
                return Message("参数错误", "指定的友情链接不存在或者已经被删除.", MessageIcon.Error);
            FriendLink.Delete(Provider, id.Value);
            return Message("删除成功", "您成功删除了该友情链接.", new { controller = "admin", action = "link" }, "返回友情链接管理", MessageIcon.Message);
        }

        [ManagerAuthorize("Config")]
        public ActionResult LinkAdd()
        {
            lb_friendlink link = new lb_friendlink();
            link.name = Request.Form["new_name"].FormEncode();
            link.url = Request.Form["new_url"].FormEncode();
            if (link.name.Length < 1 || link.url.Length < 1)
                return Message("提交数据错误", "请完整填写站点名和站点链接.", MessageIcon.Error);
            link.image = Request.Form["new_image"].FormEncode();
            link.intro = Request.Form["new_intro"].FormEncode();
            link.order = Request.Form["new_order"].ToInt32(1000);
            link.isimg = false;
            link.isindex = false;
            link.isshow = false;
            FriendLink.Insert(Provider, link);
            return Message("新增链接成功", "新增友情链接成功.", new { controller = "admin", action = "link" }, "返回友情链接管理", MessageIcon.Message);
        }

        [ManagerAuthorize("Visiter")]
        public ActionResult SysLog(int? page, int? pagesize)
        {
            page = page ?? 1;
            pagesize = pagesize ?? 20;
            ViewData.Model = Log.Get(Provider, pagesize.Value, page.Value);
            ViewData["recordcount"] = Log.Count(Provider);
            ViewData["pagesize"] = pagesize.Value;
            return View("syslog");
        }

        [ManagerAuthorize("Super")]
        public ActionResult LogClear()
        {
            Log.DeleteAll(Provider);
            return Message("操作成功", "系统日志清除成功(最近7天的不会被删除).", new { controller = "admin", action = "syslog" }, "返回日志管理", MessageIcon.Message);
        }

        public ActionResult Code() {
            return new CheckCodeResult();
        }
    }
}
